<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/10/17
 * Time: 10:00
 */
namespace App\Service\Api;

use App\Http\Model\Mysql\OrderModel;
use App\Http\Model\Mysql\OrderCommentModel;
use App\Http\Model\Mysql\OrderProductModel;
use App\Http\Model\Mysql\OrderRefundModel;
use App\Http\Model\Mysql\UserAddressModel;
use App\Http\Model\Mysql\UserMemberModel;
use App\Http\Model\Mysql\WechatOrderModel;
use App\Http\Model\Mysql\ShopModel;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Config;

class AfterService extends BaseService
{
    /**
     * 获取所有订单
     * @param int $order_status  订单状态
     * @param int $page     当前页面
     * @return array
     */
    public function afterTotal(int $order_status, int $page = 1)
    {
        $user_info  =   request()->post('api_user');

        $where['user_id']   =   $user_info['user_id'];
        $where['is_delete'] =   OrderModel::NOT_DELETE;
        $where['order_status']= OrderModel::IS_NORMAL;

        switch ($order_status) {
            case 0:         //全部
                unset($where['order_status']);
                break;

            case 1:         //未付款
                $where['is_pay']    =   OrderModel::NOT_PAY;
                break;

            case 2:         //待发货
                $where['is_pay']     =  OrderModel::IS_PAY;
                $where['send_status']=  OrderModel::NOT_SEND;
                $where['is_confirm'] =  OrderModel::NOT_CONFIRM;
                break;

            case 3:         //待收货
                $where['is_pay']     =  OrderModel::IS_PAY;
                $where['send_status']=  OrderModel::IS_SEND;
                $where['is_confirm'] =  OrderModel::NOT_CONFIRM;
                break;

            case 4:         //已完成
                $where['is_pay']     =  OrderModel::IS_PAY;
                $where['send_status']=  OrderModel::IS_SEND;
                $where['is_confirm'] =  OrderModel::IS_CONFIRM;
                break;

            case 5:
                $where['order_status']= OrderModel::IS_AFTER_SALE;
                break;
        }

        //搜索条件
        $order_list     =   OrderModel::with([
                                'product'   =>  function ($query) {
                                    $query->with([
                                        'spec'  =>  function ($query) {
                                            $query->select(['id', 'attr_list', 'sell_price', 'sku_code']);
                                        },
                                        'good'  =>  function ($query) {
                                            $query->select(['id', 'name', 'sku_code', 'cover_pic', 'sell_price', 'stock', 'unique_id']);
                                        }
                                    ])->select(['id', 'order_id', 'product_id', 'item_id', 'attr_pic', 'product_count', 'product_price']);
                                }
                            ])->where($where)->limit(self::PAGE_LIMIT)->offset(($page - 1) * self::PAGE_LIMIT)->orderBy('created_at', 'desc')->select(['id', 'order_no', 'total_price', 'send_status', 'order_status', 'is_confirm', 'refund_status', 'created_at', 'pay_price', 'is_pay', 'pay_time', 'is_comment'])->get()->each(function (&$item) {
                                $item->create_time  =   $item->created_at->toDateTimeString();
                                $item->pay_time     =   Carbon::parse($item->pay_time)->toDateTimeString();
                                unset($item->created_at);
                                $total_count    =   0;
                                //属性值
                                if (!empty($item->product)) {
                                    foreach ($item->product as &$value) {
                                        $total_count    +=  $value->product_count;
                                        $value->spec->attr_value  =   array_values(json_decode($value->spec->attr_list, true));
                                    }
                                }
                                $item->total_count  =   $total_count;

                                /**
                                 * 查看售后进度
                                 */
                                if ($item->order_status == OrderModel::IS_AFTER_SALE) {
                                    $item->after_sale   =   OrderRefundModel::where(['order_id' => $item->id, 'is_delete' => OrderRefundModel::NOT_DELETE])->select(['id', 'order_id', 'refund_no', 'refund_type', 'refund_price', 'detail_id', 'refund_status', 'is_agree'])->first() ?? [];
                                }
                            });

        return [true, $order_list->isEmpty() ? [] : $order_list->toArray()];
    }

    /**
     * 删除指定订单
     * @param string $order_number  订单号
     * @return array
     */
    public function afterDelete(string $order_number)
    {
        $user_info  =   request()->post('api_user');
        $del_result =   OrderModel::where(['user_id' => $user_info['user_id'], 'order_no' => $order_number])->update(['is_delete' => OrderModel::IS_DELETE, 'delete_time' => Carbon::now()->timestamp]);
        if ($del_result) {
            return [true, '删除成功'];
        } else {
            return [false, '删除失败'];
        }
    }

    /**
     * 取消指定订单
     * @param string $order_number  订单号
     * @param int $cancel_reason  取消原因
     * @return array
     */
    public function afterCancel(string $order_number, int $cancel_reason = 0)
    {
        $user_info  =   request()->post('api_user');
        $can_result =   OrderModel::where(['user_id' => $user_info['user_id'], 'order_no' => $order_number])->update(['order_status' => OrderModel::IS_CANCEL, 'cancel_reason' => $cancel_reason]);
        if ($can_result) {
            return [true, '取消成功'];
        } else {
            return [false, '取消失败'];
        }
    }

    /**
     * 修改订单地址
     * @param int $address_id   新的订单ID
     * @param string $order_number  订单号
     * @return array
     */
    public function afterAddress(int $address_id, string $order_number)
    {
        $user_info  =   request()->post('api_user');
        $exist_result   =   OrderModel::where(['user_id' => $user_info['user_id'], 'order_no' => $order_number, 'is_delete' => OrderModel::NOT_DELETE])->select(['order_no', 'send_status', 'is_modify'])->first();

        if (empty($exist_result)) {
            return [false, '订单不存在'];
        }

        if ($exist_result['is_modify'] == 1) {
            return [false, '已经修改过地址了'];
        }

        if ($exist_result['send_status'] == OrderModel::IS_SEND) {
            return [false, '发货中，无法修改地址'];
        }

        $address_info   =   UserAddressModel::where(['id' => $address_id, 'user_id' => $user_info['user_id'], 'is_delete' => UserAddressModel::NOT_DELETE])->select(['id', 'user_name', 'tel_number', 'province', 'city', 'area', 'address'])->first();
        if (empty($address_info)) {
            return [false, '地址不存在'];
        }

        $order_info['buyer_name']       =   $address_info['user_name'];
        $order_info['buyer_phone']      =   $address_info['tel_number'];
        $order_info['buyer_province']   =   $address_info['province'];
        $order_info['buyer_city']       =   $address_info['city'];
        $order_info['buyer_area']       =   $address_info['area'];
        $order_info['buyer_address']    =   $address_info['address'];
        $order_info['is_modify']        =   1;
        $address_result     =   OrderModel::where(['user_id' => $user_info['user_id'], 'order_no' => $order_number])->update($order_info);
        if ($address_result) {
            return [true, '修改成功'];
        } else {
            return [false, '修改成功'];
        }
    }

    /**
     * 确认订单
     * @param string $order_number  订单号
     * @return array
     */
    public function afterConfirm(string $order_number)
    {
        $user_info  =   request()->post('api_user');
        //判断是否已经发货
        $if_send    =   OrderModel::where(['user_id' => $user_info['user_id'], 'order_no' => $order_number, 'send_status' => OrderModel::IS_SEND, 'is_delete'=> OrderModel::NOT_DELETE, 'is_confirm' => OrderModel::NOT_CONFIRM])->exists();
        if (!$if_send) {
            return [false, '暂未发货'];
        }
        $confirm_result     =   OrderModel::where(['user_id' => $user_info['user_id'], 'order_no' => $order_number, 'is_delete'=> OrderModel::NOT_DELETE])->update(['is_confirm' => OrderModel::IS_CONFIRM, 'confirm_time' => Carbon::now()->timestamp]);
        if ($confirm_result) {
            return [true, '确认成功'];
        } else {
            return [false, '确认失败'];
        }
    }

    /**
     * 订单评价
     * @param array $comment
     * @param string $order_number
     * @param int $good_id
     * @return array
     */
    public function afterComment(array $comment, string $order_number, int $good_id)
    {
        $user_info  =   request()->post('api_user');

        $order_id   =   OrderModel::where(['user_id' => $user_info['user_id'], 'order_no' => $order_number])->value('id');

        $if_exist   =   OrderCommentModel::where(['user_id' => $user_info['user_id'], 'order_id' => $order_id, 'good_id' => $good_id])->value('id');

        $order_comment['user_id']   =   $user_info['user_id'];
        $order_comment['order_id']  =   $order_id;
        $order_comment['good_id']   =   $good_id;
        $order_comment['seller_star']=  $comment['seller_star'];
        $order_comment['good_star'] =   $comment['good_star'];
        $order_comment['logistic_star'] =   $comment['logistic_star'];
        $order_comment['comment']   =   $comment['comment'] ?? '';
        $order_comment['has_pic']   =   empty($comment['comment_pic']) ? 0 : 1;
        $order_comment['is_append'] =   $if_exist ? 1 : 0;
        $order_comment['append_id'] =   $if_exist ?? 0;
        $order_comment['comment_pic']   =   json_encode($comment['comment_pic'] ?? [], JSON_UNESCAPED_UNICODE);

        $comment_result     =   OrderCommentModel::create($order_comment);
        if ($comment_result) {
            OrderModel::where(['id' => $order_id])->update(['is_comment' => 1]);
            return [true, '评价成功'];
        } else {
            return [false, '评价失败'];
        }
    }

    /**
     * 订单评价商品多个
     * @param string $order_number
     * @param array $evaluate
     * @return array
     */
    public function afterEvaluate(string $order_number, array $evaluate)
    {
        $user_info  =   request()->post('api_user');
        $order_id   =   OrderModel::where(['user_id' => $user_info['user_id'], 'order_no' => $order_number])->value('id');

        $total_comment  =   [];
        foreach ($evaluate as $item) {
            $order_comment['user_id']   =   $user_info['user_id'];
            $order_comment['order_id']  =   $order_id;
            $order_comment['good_id']   =   $item['good_id'];
            $order_comment['seller_star']=  $item['seller_star'];
            $order_comment['good_star'] =   $item['good_star'];
            $order_comment['logistic_star'] =   $item['logistic_star'];
            $order_comment['comment']   =   $item['comment'] ?? '';
            $order_comment['has_pic']   =   empty($item['comment_pic']) ? 0 : 1;
            $order_comment['is_append'] =   0;
            $order_comment['append_id'] =   0;
            $order_comment['comment_pic']   =   json_encode($item['comment_pic'] ?? [], JSON_UNESCAPED_UNICODE);
            $total_comment[]    =   $order_comment;
        }

        $comment_result     =   OrderCommentModel::create($total_comment);
        if ($comment_result) {
            OrderModel::where(['id' => $order_id])->update(['is_comment' => 1]);
            return [true, '评价成功'];
        } else {
            return [false, '评价失败'];
        }
    }

    /**
     * 订单详情
     * @param string $order_number  订单号
     * @return array
     */
    public function afterDetail(string $order_number)
    {
        $user_info  =   request()->post('api_user');

        $where['user_id']   =   $user_info['user_id'];
        $where['order_no']  =   $order_number;
        $where['is_delete'] =   OrderModel::NOT_DELETE;

        $order_detail   =   OrderModel::with([
                                'product'   =>  function ($query) {             //订单产品表
                                    $query->with([
                                        'spec'  =>  function ($query) {         //产品规格表
                                            $query->select(['id', 'attr_list', 'sell_price', 'sku_code']);
                                        },
                                        'good'  =>  function ($query) {         //产品详情表
                                            $query->select(['id', 'name', 'sku_code', 'cover_pic', 'sell_price', 'stock', 'unique_id']);
                                        }
                                    ])->select(['id', 'order_id', 'product_id', 'item_id', 'attr_pic', 'product_count', 'product_total as product_price']);
                                },
                            ])->where($where)->select(['id', 'order_no', 'pay_time', 'express', 'express_no', 'total_price', 'update_price', 'send_status', 'order_status', 'is_confirm', 'refund_status', 'created_at', 'is_pay', 'coupon_price', 'pay_price', 'buyer_name', 'buyer_phone', 'buyer_province', 'buyer_city', 'buyer_area', 'buyer_address', 'send_time'])->first();
        if (empty($order_detail)) {
            return [false, '订单不存在'];
        }
        $order_detail   =   $order_detail->toArray();
        /**
         * 查看店铺的自动取消时间
         */
        $shop_setting   =   ShopModel::where(['unique_id' => '0438CBE1-0EAD-9C41-6A42-EC8241573FCF'])->select(['auto_cancel_time', 'auto_confirm_time'])->first();
        $cancel_time    =   $shop_setting['auto_cancel_time'];
        $confirm_time   =   $shop_setting['auto_confirm_time'];

        $expire_time    =   $order_detail['created_at'] + $cancel_time - Carbon::now()->timestamp;
        $expire_confirm =   $order_detail['send_time'] + $confirm_time - Carbon::now()->timestamp;
        /**
         * 如果订单已经过期，直接取消
         */
        if ($order_detail['is_pay'] == OrderModel::NOT_PAY && $expire_time <= 0) {
            $this->afterCancel($order_detail['order_no']);
        }

        if ($order_detail['send_status'] == OrderModel::IS_SEND) {
            $order_detail['expire_confirm']=  $expire_confirm;
        }

        $order_detail['expire_time']  =   $expire_time;
        $order_detail['pay_time']     =   Carbon::createFromTimestamp($order_detail['pay_time'])->toDateTimeString();
        $order_detail['created_at']   =   Carbon::createFromTimestamp($order_detail['created_at'])->toDateTimeString();
        $order_detail['send_time']    =   Carbon::createFromTimestamp($order_detail['send_time'])->toDateTimeString();
        $order_detail['is_part']      =   false;
        $order_detail['part_refund']  =   [];
        if (!empty($order_detail['product'])) {
            foreach ($order_detail['product'] as &$detail) {
                $single_refund      =   OrderRefundModel::where(['detail_id' => $detail['id'], 'order_id' => $order_detail['id'], 'is_delete' => OrderRefundModel::NOT_DELETE])->select(['id', 'order_id', 'refund_no', 'refund_type', 'refund_price', 'detail_id', 'refund_status', 'is_agree', 'response_time', 'created_at', 'reason'])->first();
                if (!empty($single_refund)) {
                    $single_refund['create_time']   =   $single_refund['created_at']->toDateTimeString();
                    $single_refund['response_time'] =   Carbon::createFromTimestamp($single_refund['response_time'])->toDateTimeString();
                    unset($single_refund['created_at']);
                }
                $detail['refund']   =   $single_refund ?? [];
                $order_detail['part_refund']  =   !empty($detail['refund']) ? $detail['refund'] : $order_detail['part_refund'];
                $order_detail['is_part']      =   $order_detail['is_part'] || empty($detail['refund']);
                if (!empty($detail['spec'])) {
                    $detail['spec']['attr_value']    =   array_values(json_decode($detail['spec']['attr_list'], true));
                }
                /**
                 * 是否已经评价
                 */
                $detail['is_comment']   =   OrderCommentModel::where(['user_id' => $user_info['user_id'], 'order_id' => $order_detail['id'], 'good_id' => $detail['good']['id']])->exists();
            }
        }
        return [true, $order_detail];
    }

    /**
     * 查看订单物流信息
     * @param string $order_number
     * @return array
     */
    public function afterExpress(string $order_number)
    {
        return [true, []];
    }

    /**
     * 订单继续支付
     * @param string $order_number
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function afterContinue(string $order_number)
    {
        $user_info      =   request()->post('api_user');
        $user_openid    =   $user_info['openid'];
        $user_id        =   $user_info['user_id'];
        $wechat_config  =   Config::get('wechat');
        $now_time       =   Carbon::now()->timestamp;

        //下单信息
        $pre_order_info =   WechatOrderModel::where(['appid' => $wechat_config['appid'], 'mch_id' => $wechat_config['mch_id'], 'out_trade_no' => $order_number])->select(['appid', 'mch_id', 'detail', 'attach', 'out_trade_no'])->first();

        $pre_order['appid']     =   $wechat_config['appid'];
        $pre_order['mch_id']    =   $wechat_config['mch_id'];
        $pre_order['nonce_str'] =   Str::random(32);
        $pre_order['body']      =   '网虹城商品购物';
        $pre_order['detail']    =   $pre_order_info['detail'] ?? $pre_order['body'];
        $pre_order['attach']    =   $pre_order_info['attach'] ?? json_encode([], JSON_UNESCAPED_UNICODE);
        $pre_order['total_fee'] =   1;      //$total_fee * 100
        $pre_order['openid']    =   $user_openid;
        $pre_order['spbill_create_ip']  =   request()->getClientIp();
        $pre_order['out_trade_no']      =   $order_number;
        $pre_order['time_start']        =   Carbon::now()->format('YmdHis');
        $pre_order['time_expire']       =   Carbon::parse("+2 hours")->format('YmdHis');
        $pre_order['notify_url']        =   $wechat_config['notify_url'];
        $pre_order['trade_type']        =   'JSAPI';
        $pre_order['sign']      =   wechatEncrypt($pre_order, $wechat_config['mch_key']);

        /**
         * 保存预下单记录
         */
        $pre_order_model    =   WechatOrderModel::create($pre_order);

        /**
         * 发起预下单请求
         */
        try {
            $query_client   =   new Client(['verify' => false, 'timeout' => 5]);
            $query_response =   $query_client->post('https://api.mch.weixin.qq.com/pay/unifiedorder', ['body' => xmlEncode($pre_order)]);
        } catch (\Exception $e) {
            return [false, $e->getMessage()];
        }
        $xml_data       =   $query_response->getBody()->getContents();
        $query_result   =   xmlObjectToArray(simplexml_load_string($xml_data, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS | LIBXML_NOERROR));

        /**
         * 预下单请求处理
         */
        if ($query_result['return_code'] == 'FAIL') {
            return [false, $query_result['return_msg']];
        } else {
            $pre_order_model->err_code      =   $query_result['err_code'] ?? '';
            $pre_order_model->err_code_desc =   $query_result['err_code_desc'] ?? '';
            if ($query_result['result_code'] == 'SUCCESS') {
                $pre_order_model->prepay_id =   $query_result['prepay_id'] ?? '';
                $pre_order_model->code_url  =   $query_result['code_url'] ?? '';
                $pre_order_model->save();

                $pay_param  =   [
                    'timeStamp' =>  $now_time,
                    'nonceStr'  =>  $pre_order['nonce_str'],
                    'signType'  =>  'MD5',
                    'package'   =>  'prepay_id=' . $pre_order_model->prepay_id,
                    'appId'     =>  $wechat_config['appid']
                ];
                $pay_param['paySign']   =   wechatEncrypt($pay_param, $wechat_config['mch_key']);
                return [true, $pay_param];
            } else {
                return [false, '购买记录出错'];
            }
        }
    }

}
